#include "MyWebServer.h"
#include "Common.h"
#include "BlockFileHandler.h"
#include <avr/pgmspace.h>
#include "HTML.h"

/**
 * @brief 构造函数
 * @param  
 */
MyWebServer::MyWebServer(void)
{
  _server = new ESP8266WebServer(80);
  _status = WEBSERVER_STATUS::INIT;
}

/**
 * @brief 析构方法
 * @param
 */
MyWebServer::~MyWebServer(void)
{
  delete _server;
}

/**
 * @brief 初始化服务器配置
 * @param
 */
void MyWebServer::init(void)
{
  _server->on("/", [this](){this->req_index();});
  _server->on("/config", [this](){this->req_config();});
  _server->onNotFound([this](){this->req_404();});
  _server->begin();
}

/**
 * @brief 状态机
 * @param  
 */
void MyWebServer::stateMachine(void)
{
  switch (_status)
  {
  //初始化状态
  case WEBSERVER_STATUS::INIT:
    LOG("[webserver] init");
    init();
    _status = WEBSERVER_STATUS::RUNNING;
    break;

  //运行状态
  case WEBSERVER_STATUS::RUNNING:
    //LOG("[webserver] running");
    _server->handleClient();
    break;
  
  default:
    _status = WEBSERVER_STATUS::INIT;
    break;
  }
}

/**
 * @brief 404页面处理
*/
void MyWebServer::req_404(void)
{
  LOG("/404");
  _server->send(404, "text/plain", "404");
}


/**
 * @brief "/"处理【配置模式】
*/
void MyWebServer::req_index(void)
{
  LOG("/");
  _server->send_P(200, "text/html", _HTML);
}


/**
 * @brief "/config"处理
*/
void MyWebServer::req_config(void)
{
  String items[7];
  items[0] = _server->arg("ssid");
  items[1] = _server->arg("pwd");
  items[2] = _server->arg("server");
  items[3] = _server->arg("port");
  items[4] = _server->arg("token");
  items[5] = _server->arg("topic0");
  items[6] = _server->arg("topic2");

  LOG_F("/config ssid=[%s] pwd=[%s] ", items[0], items[1]);
  LOG_F("server=[%s] port=[%s] token=[%s] topic=[%s] pin=[%s]\n", items[2], items[3], items[4], items[5], items[6]);

  if (items[0] == "" || items[1] == "") {
    _server->send(500, "text/plain", "ERR");
  }

  BlockFileHandler bfh;
  bfh.write(CONFIG_FILE, items, 7);
  
  _server->send(200, "text/plain", "OK");
}
